package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.Bindable;
import android.net.Uri;
import android.view.View;

import com.solidfire.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.NotifyParentCheckedChanged;
import chuangyi.com.org.DOMIHome.ParagraphEditor;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.Utils.OSSUtil;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/12/12.
 */

public class ArticleEditorBase extends ObservableWithGoBackHandler
        implements WaitActivityResult, ParagraphEditor, NotifyParentCheckedChanged {
    private Integer id;
    private boolean updating;
    private String content;
    private String label;
    private String title;
    private ParagraphItem currentUpdate;
    private ListBindingAdapter<ParagraphItem> paragraphs;
    private ListBindingAdapter hotTags;
    private ListBindingAdapter normalTags;

    protected boolean isArticle() {
        return true;
    }

    @Override
    public Integer getId() {
        return id;
    }

    protected void setId(int id) {
        this.id = id;
    }

    @Bindable
    public boolean isUpdating() {
        return updating;
    }

    public void setUpdating(boolean updating) {
        this.updating = updating;
        notifyPropertyChanged(BR.updating);
    }

    @Bindable
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
        notifyPropertyChanged(BR.content);
    }

    public ParagraphItem getCurrentUpdate() {
        return currentUpdate;
    }

    protected void setCurrentUpdate(ParagraphItem currentUpdate) {
        this.currentUpdate = currentUpdate;
    }

    @Bindable
    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
        notifyPropertyChanged(BR.label);
    }

    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }

    @Bindable
    public ListBindingAdapter<ParagraphItem> getParagraphs() {
        return paragraphs;
    }

    @Bindable
    public ListBindingAdapter getHotTags() {
        return hotTags;
    }

    @Bindable
    public ListBindingAdapter getNormalTags() {
        return normalTags;
    }

    protected ArticleEditorBase(Context context) {
        super(context);
        List<Integer> viewTypeList = new ArrayList<Integer>();
        viewTypeList.add(R.layout.i_edit_image_paragraph);
        viewTypeList.add(R.layout.i_edit_text_paragraph);
        paragraphs = new ListBindingAdapter<ParagraphItem>(getContext(), BR.paragraph, viewTypeList);
        hotTags = new ListBindingAdapter(getContext(), BR.tag);
        normalTags = new ListBindingAdapter(getContext(), BR.tag);
        initTags();
    }

    public void load() {
        paragraphs.setNotifyOnChange(false);
        paragraphs.clear(true);
    }

    protected boolean addParagraph(ParagraphItem item) {
        LinkedTreeMap map = WebApi.addParagraph(getContext(), id, label, title, item, isArticle());
        Integer paragraphId = null;
        if (isArticle()) {
            paragraphId = Utils.getIntegerValue(map.get("colid"));
            this.setId(Utils.getIntValue(map.get("docid")));
        } else {
            paragraphId = Utils.getIntegerValue(map.get("askid"));
            this.setId(Utils.getIntValue(map.get("questionid")));
        }
        if (paragraphId != null) {
            item.setId(paragraphId);
            item.setParent(this);
            paragraphs.add(item);
            if (updating) {
                setUpdating(false);
            }
            setContent("");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    paragraphs.notifyDataSetChanged();
                }
            });
            return true;
        } else {
            return false;
        }
    }

    /**
     * 点击添加文字
     *
     * @param view
     */
    public void onClickAddParagraph(View view) {
        if (getContent() == null || getContent().equals("")) {
            showToast("文章内容不能为空");
            return;
        }
        if (getTitle() == null || getTitle().equals("")) {
            showToast("标题不能为空");
            return;
        }
        if (getLabel() == null || getLabel().equals("")) {
            showToast("标签不能为空");
            return;
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (updating) {
                        if (currentUpdate == null) {
                            LoadingDialog.getInstance(getContext()).dismiss();
                            return;
                        }
                        if (WebApi.updateParagraph(getContext(), currentUpdate.getId(), content, isArticle())) {
                            currentUpdate.setContent(content);
                            setUpdating(false);
                            setContent("");
                        }
                    } else {
                        ParagraphItem item = new ParagraphItem(getContext(), ParagraphItem.TEXT_PARAGRAPH);
                        item.setContent(content);
                        item.setAllowEdit(true);
                        addParagraph(item);
                    }
                } catch (Exception ex) {

                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 点击添加图片
     *
     * @param view
     */

    public void onClickAddImage(View view) {
        showSelectPhoto(null);
    }

    /**
     * 点击保存到草稿箱按钮
     *
     * @param view
     */
    public void onClickSave(View view) {
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 点击发布按钮
     *
     * @param view
     */
    public void onClickPublish(View view) {

    }

    private void addTag(String tag) {
        if (label == null || "".equals(label)) {
            setLabel(tag + ";");
        } else {
            if (label.endsWith(";")) {
                setLabel(label + tag + ";");
            } else {
                setLabel(label + ";" + tag + ";");
            }
        }
    }

    private void removeTag(String tag) {
        if (label != null && !label.equals("")) {
            int index = label.indexOf(tag);
            if (index == -1) {
                return;
            } else {
                if (index + tag.length() < label.length()) {
                    if (label.charAt(index + tag.length()) == ';') {
                        setLabel(label.replace(tag + ";", ""));
                    } else {
                        label.replace(tag, "");
                    }
                } else {
                    setLabel(label.replace(tag, ""));
                }
            }
            notifyPropertyChanged(BR.label);
        }
    }

    private void showSelectPhoto(Integer paragraphId) {
        Activity activity = (Activity) getContext();
        Intent intent = new Intent();
        intent.setClass(activity, PopupActivity.class);
        PopupActivity.setDataModel(new SelectPhotoModel(activity));
        intent.putExtra("layoutId", R.layout.v_dialog_modify_photo);
        intent.putExtra("variableId", BR.photoSelector);
        intent.putExtra("paragraphId", paragraphId == null ? -1 : paragraphId);
        activity.startActivityForResult(intent, HomeActivity.REQUEST_IMAGE);
    }

    public void initTags() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    LinkedTreeMap result = WebApi.getLabel(getContext());
                    if (result == null) {
                        return;
                    }
                    ArrayList list = (ArrayList) result.get("hotlabels");
                    for (Object item : list) {
                        LinkedTreeMap map = (LinkedTreeMap) item;
                        CheckedMenuItem menuItem = new CheckedMenuItem(getContext(), R.layout.i_tag);
                        menuItem.setTitle((String) map.get("title"));
                        menuItem.setParent(ArticleEditorBase.this);
                        hotTags.add(menuItem);
                    }
                    notifyDataSetChanged(hotTags);

                    list = (ArrayList) result.get("usedlabels");
                    for (Object item : list) {
                        LinkedTreeMap map = (LinkedTreeMap) item;
                        CheckedMenuItem menuItem = new CheckedMenuItem(getContext(), R.layout.i_tag);
                        menuItem.setTitle((String) map.get("title"));
                        menuItem.setParent(ArticleEditorBase.this);
                        normalTags.add(menuItem);
                    }
                    notifyDataSetChanged(normalTags);
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
            }
        }).start();
//        for (int i = 0; i < 5; i++) {
//            CheckedMenuItem item = new CheckedMenuItem(getContext(), R.layout.i_tag);
//            item.setTitle("标签" + String.valueOf(i + 1));
//            item.setParent(this);
//            hotTags.add(item);
//        }
//        for (int i = 0; i < 5; i++) {
//            CheckedMenuItem item = new CheckedMenuItem(getContext(), R.layout.i_tag);
//            item.setTitle("常用标签" + String.valueOf(i + 1));
//            item.setParent(this);
//            normalTags.add(item);
//        }
    }

    @Override
    public void notifyCheckedChanged(CheckedMenuItem menu) {
        if (menu.getTitle() == null || menu.getTitle().equals("")) {
            return;
        }
        if (menu.isChecked()) {
            addTag(menu.getTitle());
        } else {
            removeTag(menu.getTitle());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == HomeActivity.REQUEST_IMAGE) {
                final Uri uri = data.getData();
                final int paragraphId = data.getIntExtra("paragraphId", -1);
                LoadingDialog.getInstance(getContext()).show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String fileName = Utils.getPathByUri(uri, getContext());
                            String url = OSSUtil.uploadFile(getContext().getApplicationContext(), fileName);

                            // 新增图片段落
                            if (paragraphId == -1) {
                                ParagraphItem item = new ParagraphItem(getContext(), ParagraphItem.IMAGE_PARAGRAPH);
                                item.setAllowEdit(true);
                                item.setContent(url);
                                addParagraph(item);
                            } else {
                                for (int index = 0; index < paragraphs.getCount(); index++) {
                                    ParagraphItem item = (ParagraphItem) paragraphs.getItem(index);
                                    if (item.getId() == paragraphId) {
                                        item.setContent(url);
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            showToast(ex.getMessage());
                        }
                        LoadingDialog.getInstance(getContext()).dismiss();
                    }
                }).start();
            }
        }
    }

    @Override
    public void removeParagraph(final ParagraphItem item) {
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (WebApi.deleteParagraph(getContext(), getId(), item.getId(), isArticle())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            paragraphs.remove(item);
                            paragraphs.notifyDataSetChanged();
                        }
                    });
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    @Override
    public void moveUpParagraph(final ParagraphItem item) {
        LoadingDialog.getInstance(getContext()).show();
        final int index = paragraphs.getPosition(item);
        if (index <= 0) {
            LoadingDialog.getInstance(getContext()).dismiss();
            return;
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (WebApi.upMoveParagraph(getContext(), getId(), item.getId(), isArticle())) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                paragraphs.remove(item);
                                paragraphs.insert(item, index - 1);
                                paragraphs.notifyDataSetChanged();
                            }
                        });
                    }
                    LoadingDialog.getInstance(getContext()).dismiss();
                }
            }).start();
        }
    }

    @Override
    public void moveDownParagraph(final ParagraphItem item) {
        LoadingDialog.getInstance(getContext()).show();
        final int index = paragraphs.getPosition(item);
        if (index >= paragraphs.getCount() - 1) {
            LoadingDialog.getInstance(getContext()).dismiss();
            return;
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (WebApi.downMoveParagraph(getContext(), getId(), item.getId(), isArticle())) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                paragraphs.remove(item);
                                paragraphs.insert(item, index + 1);
                                paragraphs.notifyDataSetChanged();
                            }
                        });
                    }
                    LoadingDialog.getInstance(getContext()).dismiss();
                }
            }).start();
        }
    }

    @Override
    public void updateParagraph(final ParagraphItem item) {
        if (item.getContentType() == ParagraphItem.IMAGE_PARAGRAPH) {
            showSelectPhoto(item.getId());
        } else {
            if (updating) {
                showToast("正在编辑其它文字");
                return;
            }
            currentUpdate = item;
            setContent(item.getContent());
            setUpdating(true);
        }
    }
}
